package com.example.client;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;


import com.example.client.aidl.IRemote;
import com.example.client.aidl.IRemoteImpl;
import com.example.ipcdemo.TaskInfo;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private IRemote mBinder;
    private RemoteService mRemoteService;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent();

        //绑定 AIDL 服务
        intent.setClassName("com.example.ipcdemo","com.example.ipcdemo.service.RemoteService");
        mRemoteService = new RemoteService();
        bindService(intent,mRemoteService, Service.BIND_AUTO_CREATE);
    }

    class RemoteService implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBinder = IRemoteImpl.asInterface(service);
          //  mBinder = IRemoteService.Stub.asInterface(service);
            try {
                mBinder.asBinder().linkToDeath(mDeathRecipient,0);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }


    public void testAidl(View view) {
        try {
            if (mBinder != null) {
                TaskInfo info = new TaskInfo();
                info.url = "www.google.com";
                TaskInfo taskInfo = mBinder.addTask(info);

                int num = mBinder.add(2,3);

                Log.d(TAG, "zsr testAidl: 获取到服务端数据: "+taskInfo+" "+num);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }


    IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
        @Override
        public void binderDied() {
            Log.d(TAG, "zsr binderDied: ");
            if (mBinder != null) {
                mBinder.asBinder().unlinkToDeath(mDeathRecipient,0);
                mBinder = null;
                //todo 执行重新绑定service 的逻辑
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mBinder != null) {
            mBinder.asBinder().unlinkToDeath(mDeathRecipient,0);
        }
        if (mRemoteService != null) {
            unbindService(mRemoteService);
        }

    }
}
